<?php
// 声明编码
header("Content-Type:text/html;charset=utf-8");

//临时改变单个脚本的环境参数
//用函数来设置脚本的运行时间 0 不限制时间 临时改动
set_time_limit(0); //设置脚本运行时间为0

// 给一个默认 user_agent 让他认为自己是浏览器
ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)');

$url = "https://www.bizhi99.com/c18/";

//网页内容获取
$html = file_get_contents($url);

if(empty($html))
{
    echo "未获取到网页内容\r\n";
    exit;
}

// 开始标记：<div class="auto mt">
// 结束标记：</div>
$reg = "/<div\s*class=\"auto\s*mt\">.*共拥有(\d+)/ims";
preg_match($reg, $html, $res);

$count = isset($res[1]) ? trim($res[1]) : 0;

if($count <= 0)
{
    echo "未获取到总张数\r\n";
    exit;
}

//每页显示多少条数据
$limit = 36;

//算出总页数   11.3 = 12 多出来的放到新的页面里面
$pages = ceil($count / $limit);

if($pages <= 0)
{
    echo "为获取到总页数\r\n";
    exit;
}

$links = [];

for($i=1; $i <= $pages; $i++)
{
    $links[] = $url."$i.html";
}

echo "开始采集\r\n";
$pics = [];

//每一页进行循环遍历
foreach($links as $key=>$item)
{
    $cur = $key + 1;

    //每一页进行获取
    $content = file_get_contents($item);

    if(empty($content))
    {
        echo "采集【第 $cur 页】内容为空\r\n";
        continue;
    }

    echo "开始采集【第 $cur 页】\r\n";

    // <img class="lazy" src="https://static.dmjnb.com/static/index/images/loading.png" data-original="https://pic.dmjnb.com/pic/ee9824a316a783d77a2ddaefdb69954f?imageMogr2/thumbnail/x380/quality/90!" alt="炫酷特效星空宇宙高清壁纸">
    $reg = "/data-original=\"(.*)\"/imsU";
    preg_match_all($reg, $content, $res);
    
    if(empty($res[1]))
    {
        echo "采集【第 $cur 页】图片列表为空\r\n";
        continue;
    }

    //数组合并
    $pics = array_merge($pics, $res[1]);
}

//去空
$pics = array_filter($pics);

if(empty($pics))
{
    echo "未采集到图片\r\n";
    exit;
}

//创建存放的目录
$path = "./photo";
$res = mkdir($path, 0777, true);

if(!$res)
{
    echo "存放目录创建失败\r\n";
    exit;
}

echo "开始采集图片\r\n";

$success = $fail = 0;

foreach($pics as $key=>$item)
{
    $cur = $key + 1;

    //采集图片其实和文件读取内容和写入内容
    $bitdata = file_get_contents($item);

    //组装保存的文件名称
    $filename = $path.'/'.$cur.".png";

    //写入内容
    $length = file_put_contents($filename, $bitdata);

    if($length <= 0)
    {
        echo "第【{$cur}】张 采集失败\r\n";
        $fail++;
    }else
    {
        echo "第【{$cur}】张 采集成功\r\n";
        $success++;
    }

    sleep(0.5); //延迟
}

echo "采集完毕，共 $count 张, 成功采集：$success 张 失败采集：$fail 张\r\n";